package org.example.repository;

import org.example.entity.DeviceControlLog;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 设备控制记录数据访问接口
 */
@Repository
public interface DeviceControlLogRepository extends JpaRepository<DeviceControlLog, Long> {
    
    /**
     * 根据设备ID查找控制记录
     */
    List<DeviceControlLog> findByDeviceId(Long deviceId);
    
    /**
     * 根据用户ID查找控制记录
     */
    List<DeviceControlLog> findByUserId(Long userId);
    
    /**
     * 根据设备ID和用户ID查找控制记录
     */
    List<DeviceControlLog> findByDeviceIdAndUserId(Long deviceId, Long userId);
    
    /**
     * 根据操作动作查找控制记录
     */
    List<DeviceControlLog> findByAction(String action);
    
    /**
     * 根据时间范围查找控制记录
     */
    List<DeviceControlLog> findByControlTimeBetween(LocalDateTime startTime, LocalDateTime endTime);
    
    /**
     * 分页查询设备控制记录
     */
    Page<DeviceControlLog> findByDeviceId(Long deviceId, Pageable pageable);
    
    /**
     * 分页查询用户控制记录
     */
    Page<DeviceControlLog> findByUserId(Long userId, Pageable pageable);
    
    /**
     * 统计设备控制次数
     */
    @Query("SELECT COUNT(dcl) FROM DeviceControlLog dcl WHERE dcl.deviceId = :deviceId")
    long countByDeviceId(@Param("deviceId") Long deviceId);
    
    /**
     * 统计用户操作次数
     */
    @Query("SELECT COUNT(dcl) FROM DeviceControlLog dcl WHERE dcl.userId = :userId")
    long countByUserId(@Param("userId") Long userId);
    
    /**
     * 查找最近的设备控制记录
     */
    @Query("SELECT dcl FROM DeviceControlLog dcl WHERE dcl.deviceId = :deviceId ORDER BY dcl.controlTime DESC")
    List<DeviceControlLog> findRecentByDeviceId(@Param("deviceId") Long deviceId, Pageable pageable);
}
